﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Business;
using Models;
using System.IO;
using System.Collections;
using System.Drawing;

//using DataAccess;
using System.Data;

public partial class client_TechnicalDataSheet : @base
{
    DataTable components = new DataTable();
    DataTable selectedComponents = new DataTable();
    DataTable data = new DataTable();
    DataTable showData = new DataTable();
    bool change = false;
    DataSheetService ds = new DataSheetService();
    ReportServices rs = new ReportServices();
    List<int> indexes = new List<int>();
    bool[] rowChanged;
   // bool dt = true;
    int option = 0;
    private void BindData()
    {
        GridView1.DataSource = Session["TaskTable"];
        GridView1.DataBind();
        GridView1.ShowHeader = false;

    }
   
        
    protected void Page_Load(object sender, EventArgs e)
    {
        int totalRows = GridView1.Rows.Count;
        rowChanged = new bool[totalRows];
       // indexes = new List<int>();
        if (UserDetails == null)
        {
            string message = "User has been logged out!";
            Server.Transfer("ErrorMessage.aspx?message=" +message );
        }
        if (!IsPostBack)
        {
            MachineNameLabel.Text = "Technical Data Sheet for " + MACHINENAME;
            save.Visible = false;        

        }
        else
            if (option == 1)
            {
                setShowData();
                if (UserDetails.Role == "Admin")
                {
                    save.Visible = true;
                }
                int n = showData.Rows.Count;
                Session["TaskTable"] = showData;
                BindData();
            }
            ///
            
    }
    protected void Component_changed(object sender, EventArgs e)
    {

        if (SelectComponent_DropDownList.SelectedValue == "Choose Components")
        {
            if (change == false)
            {
                components = rs.getcomponentsByMachine(MACHINEID);
                change = true;
            }
            foreach (DataRow site in components.Rows)
            {
                String siteName = site["componentName"].ToString();
                string siteID = site["component_id"].ToString();

                System.Web.UI.WebControls.ListItem ls = new System.Web.UI.WebControls.ListItem(siteName, siteID, true);
                ComponentsCheckBoxList.Items.Add(ls);
            }

        }
        else
        {
            ComponentsCheckBoxList.Items.Clear();
        }

    }
    protected DataTable getSelectedComponent()
    {
        DataTable SC = new DataTable();
        SC.Columns.Add("componentName", typeof(string));
        SC.Columns.Add("component_id", typeof(int));
        if (SelectComponent_DropDownList.SelectedValue == "Choose Components")
        {

            foreach (System.Web.UI.WebControls.ListItem lt in ComponentsCheckBoxList.Items)
            {

                if (lt.Selected)
                {
                    string componentName = "";
                    componentName = lt.Text;
                    int componentID = Int32.Parse(lt.Value);
                    SC.Rows.Add(componentName, componentID);
                }
            }
        }
        else
        {
            if (change == false)
            {
                components = rs.getcomponentsByMachine(MACHINEID);
                change = true;
            }
            SC = components;

        }
        return SC;
    }
    private void bindData()
    {

        GridView1.DataSource = showData;
        GridView1.DataBind();

    }
    protected void gvFoo_RowDataBound(object sender, GridViewRowEventArgs e)
    {
       if (e.Row.RowType == DataControlRowType.DataRow)
        {
            int i = e.Row.DataItemIndex;

            TextBox tb1 = (TextBox)e.Row.FindControl("TextBox1");
            tb1.Text = ((DataTable)(Session["TaskTable"])).Rows[i]["Attributes"].ToString();
            TextBox tb2 = (TextBox)e.Row.FindControl("TextBox2");
            tb2.Text = ((DataTable)(Session["TaskTable"])).Rows[i]["Values"].ToString();
           if (indexes[i] == 1)
           {
               tb2.ReadOnly = true;
               tb1.Font.Size = 14;
               tb1.ForeColor = Color.Red;
               tb1.Font.Bold = true;
               tb1.Style["text-align"] = "center";

           }
           else
               tb1.ForeColor = Color.SeaGreen;           
           
        }
        
    }
    protected void TextBox_TextChanged(object sender, EventArgs e)
    {
        TextBox thisTextBox = (TextBox)sender;
        GridViewRow thisGridViewRow = (GridViewRow)thisTextBox.Parent.Parent;
        int row = thisGridViewRow.RowIndex;
        rowChanged[row] = true;
    }

    protected void Page_PreRender(object sender, EventArgs e)
    {
        if (Page.IsPostBack)
        {

            if (option == 2)
            {
                DataTable table = (DataTable)Session["TaskTable"];
                DataTable newTable = new DataTable();
                DataTable updateTable = new DataTable();
                updateTable = getDatatable();
                updateTable.Columns.Add("component_id", typeof(int));
                int component_id=0;
                newTable = getDatatable();
                indexes = (List<int>)Session["indexes"];
                selectedComponents = (DataTable)Session["selectedComponents"];
                int count = selectedComponents.Rows.Count;

                int totalRows = GridView1.Rows.Count;


                // string sql = "";

                for (int r = 0; r < totalRows; r++)
                {
                    
                    if (indexes[r] == 1)
                    {
                        string componentName=table.Rows[r]["Attributes"].ToString();
                        DataRow[] component_ids = selectedComponents.Select("componentName = '" + componentName+"'");
                        foreach (DataRow comp in component_ids)
                        {
                            component_id = ToInt(comp["component_id"].ToString());
                        }
                    }
                    if (rowChanged[r])
                    {
                        GridViewRow thisGridViewRow = GridView1.Rows[r];
                        HiddenField hf1 = (HiddenField)thisGridViewRow.FindControl("HiddenField1");
                        string pk = hf1.Value;
                        TextBox tb1 = (TextBox)thisGridViewRow.FindControl("TextBox1");
                        string cell1 = tb1.Text;
                        TextBox tb2 = (TextBox)thisGridViewRow.FindControl("TextBox2");
                        string cell2 = tb2.Text;
                        //sql = "update project set project_number='" + cell1 + "', description='" + cell2 + "', manager='" + cell3 + "' where id=" + pk;
                        DataRow tableRo = newTable.NewRow();
                       // tableRo["Index"] = pk;
                        tableRo["Attributes"] = cell1;

                        tableRo["Values"] = cell2;

                        newTable.Rows.Add(tableRo);
                        DataRow updateRow = updateTable.NewRow();
                        updateRow["Attributes"] = cell1.Substring(0,cell1.Length-1);
                        updateRow["Values"] = cell2;
                        updateRow["component_id"] = component_id;
                        updateTable.Rows.Add(updateRow);

                    }
                    else
                    {
                        DataRow row = newTable.NewRow();
                        //row["Index"] = table.Rows[r]["Index"].ToString();
                        row["Attributes"] = table.Rows[r]["Attributes"].ToString();

                        row["Values"] = table.Rows[r]["Values"].ToString();


                        newTable.Rows.Add(row);
                    }

                }
               
                ds.updateDataByID(updateTable);
                showData = newTable;
                Session["TaskTable"] = newTable;

                int t = showData.Rows.Count;
                int c = showData.Columns.Count;
                string attribute = showData.Rows[0]["Attributes"].ToString();
                string value = showData.Rows[0]["Values"].ToString();
                GridView1.DataSource = showData;
                GridView1.DataBind();
                option = 0;
            }
            else
                option = 0;
      
        }         
        

    }
    private DataTable getDatatable()
    {
        DataTable taskTable = new DataTable();
        //option = 1;
      //  taskTable.Columns.Add("Index", typeof(int));
        taskTable.Columns.Add("Attributes", typeof(string));
        taskTable.Columns.Add("Values", typeof(string));
        return taskTable;
    }
    protected void setShowData()
    {
        selectedComponents = getSelectedComponent();
        data = ds.getDataByComponentID(selectedComponents);
        Session["selectedComponents"] = selectedComponents;
        int count = selectedComponents.Rows.Count;
        showData = getDatatable();
        int num_row = -1;
        foreach (DataRow r in selectedComponents.Rows)
        {
            num_row++;
            int componentId = ToInt(r["component_id"].ToString());
            DataRow[] componentData = data.Select("component_id = " + componentId);
            DataRow tableRow = showData.NewRow();
           // tableRow["Index"] = num_row;
            tableRow["Attributes"] = r["componentName"].ToString();
            tableRow["Values"] = "";
            showData.Rows.Add(tableRow);
            indexes.Add(1);
            foreach (DataRow crow in componentData)
            {
                num_row++;
                DataRow trow = showData.NewRow();
               // trow["Index"] = num_row;
                trow["Attributes"] = crow["Attribute"].ToString() + ":";
                trow["Values"] = crow["Value"].ToString();
                showData.Rows.Add(trow);
                indexes.Add(0);

            }
        }
        int t = showData.Rows.Count;
        Session["indexes"] = indexes;
        
    }
    protected void GetDataSheet(object sender, EventArgs e)
    {
        option = 1;
        setShowData();
        Session["TaskTable"] = showData;// taskTable;

        //Bind data to the GridView control.

        BindData();
        //Enable Save button
        if (UserDetails.Role == "Admin")
        {
            save.Visible = true;
        }

    }
    
    protected void Button1_Click(object sender, EventArgs e)
    {
        option = 2;
        
    }
}
